﻿using LiteDB;
using MyWPF.Models.UserManagement;
using MyWPF.ViewModel.User;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWPF.Models.Recipe
{
    public class RecipeHelper : IRecipe
    {

        private LiteDatabase DB;
        private ILiteCollection<RecipeContext> Recipes;


        public void LoadDB(RecipeDbContext RecipeDb)
        {
            if (!Directory.Exists(RecipeDb.Path)) // 如果文件夹不存在
            {
                Directory.CreateDirectory(RecipeDb.Path); // 创建文件夹
            }

            //创建数据库
            string Filename = Path.Combine(RecipeDb.Path, RecipeDb.DbName);
            DB = new LiteDatabase("Filename=" + Filename + ";Password=" + RecipeDb.Password);
            //新建表
            Recipes = DB.GetCollection<RecipeContext>("Recipes");

        }


        public bool AddRecipe(RecipeContext Recipe)
        {
            //如果之前就存在同名配方就不允许继续创建
            if (GetContextsStruct_Name(Recipe).Length == 0)
            {
                Recipes.Insert(Recipe);
                return true;
            }
            else
            {
                return false;
            }
        }

        public void RemoveRecipe(RecipeContext Recipe)
        {
            Recipes.DeleteMany(x => x.Name == Recipe.Name);
        }

        public void ModifyRecipe(RecipeContext Recipe)
        {
            Recipe._id = GetContextsStruct_Name(Recipe)[0]._id;
            Recipes.Update(Recipe._id, Recipe);
        }

        public RecipeContext[] GetContextsStruct()
        {
            return Recipes.FindAll().ToArray();
        }

        public RecipeContext[] GetContextsStruct_Name(RecipeContext Recipe)
        {
            return Recipes.Find(x => x.Name == Recipe.Name).ToArray();
        }
    }
}